/**
 * @author 黄波
 * 创建日期：2011Oct 5, 2011
 * TODO// N/A
 */
package com.platform.njcc.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.platform.constant.SaveDir;
import com.platform.os.util.Util;
import com.platform.pojo.ResInfo;
import com.platform.pojo.UserInfo;
import com.platform.res.bo.ResBo;
import com.platform.user.bo.UserBo;

/**
 * 上传操作
 */
public class UploadAction extends NJCCSuport {
	private String shareType;	//共享方式
	private String type;	//资源类型
	private String tag;		//资源标签
	private String resScore;//资源下载所要分类
	private String resDes;	//资源描述
	private String classId;	//资源对应班级号
	private String folderId;	//资源对应课程文件夹号
	/* 批量文件上传 */
    private File[] upload;
    private String[] uploadContentType;
    private String[] uploadFileName;
    /* 资源缩略图 */
    private File resIcon;
    private String resIconContentType;
    private String resIconFileName;
    private String resIconMsg;
    
    private String[] msg;
    public String[] getMsg() {
		return msg;
	}
	public void setMsg(String[] msg) {
		this.msg = msg;
	}
	private String getSavePath() throws Exception {
        return ServletActionContext.getRequest().getRealPath(SaveDir.BASE_RESOURCE_DIR);
    }
	public File[] getUpload() {
		return upload;
	}
	public void setUpload(File[] upload) {
		this.upload = upload;
	}
	public String[] getUploadContentType() {
		return uploadContentType;
	}
	public void setUploadContentType(String[] uploadContentType) {
		this.uploadContentType = uploadContentType;
	}
	public String[] getUploadFileName() {
		return uploadFileName;
	}
	public void setUploadFileName(String[] uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	@Override
	public String execute() throws Exception {
		
		//取前用户USERID
		HttpSession session = ServletActionContext.getRequest().getSession();
		UserInfo user = (UserInfo)session.getAttribute("user");
		if(user == null) {
			//用户未登录
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.flush();
			out.write("<script>alert('请登录后继续上传！');window.location.href='../login.jsp?refreshurl=upload.jsp';</script>");
			out.close();
			return null;
		}
		if(user.getIsAudit().intValue() != 1) {
			//用户未登录
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.flush();
			out.write("<script>alert('帐户锁定中，不能上传资源，请联系管理员解锁！');history.back();</script>");
			out.close();
			return null;
		}
		//加载系统配置文件
		String systemProfile = "/system.properties";
		InputStream stream = new FileInputStream(new File(ServletActionContext.getServletContext().getRealPath("/") + systemProfile));
		Properties properties = new Properties();
		properties.load(stream);
		stream.close();
		int iconSize = Integer.parseInt(properties.get("icon_size").toString());
		int contentSize = Integer.parseInt(properties.get("content_size").toString());
		String iconUrl = null;
        //上传资源icon
        if(resIcon != null){
			//处理文件太大或不符规则等问题
			if(resIcon.length() > iconSize*1024*1024) {
		        resIconMsg = "资源缩略图上传失败，文件过大！";
		        Util.clearTMPFolder();
			} else {
				//此处使用UUID，防止文件重名
				File targetFile = new File(getSavePath() + "\\" + UUID.randomUUID().toString() + System.currentTimeMillis() + getResIconFileName().substring(getResIconFileName().indexOf(".")));
	//			File targetFile = new File(getSavePath() + "\\" + getUploadFileName()[i]);
				File targetDir = new File(getSavePath());
				if(!targetDir.exists()) {
					targetDir.mkdirs();
				}
				//文件重名则上能上传
				if(targetFile.exists()) {
			        resIconMsg = "资源缩略图上传失败，存在重名文件！";
				} else {
					if(!targetFile.exists()) {
						targetFile.createNewFile();
					}
					//以服务器的文件保存地址和原文件名建立上传文件输出流
					FileOutputStream fos = new FileOutputStream(getSavePath() + "\\" + targetFile.getName());
					FileInputStream fis = new FileInputStream(resIcon);
					byte[] buffer = new byte[1024];
					int len = 0;
					while ((len = fis.read(buffer)) > 0){
						fos.write(buffer , 0 , len);
					}
			        fos.close();// 注意：流应当关闭。
			        fis.close();
			        iconUrl = SaveDir.BASE_RESOURCE_DIR + "/" + targetFile.getName();
				}
			}
        }
		//批量上传文件
        int count = 0;	//统计上传成功的资源
		File[] files = getUpload();
		if(files == null) {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.flush();
			out.write("<script>alert('上传文件不得为空！');history.back();</script>");
			out.close();
			return null;
		}
		msg = new String[files.length];
		for (int i = 0 ; i < files.length ; i++){
			File item = files[i];
			//处理文件太大或不符规则等问题
			if(item.length() > contentSize*1024*1024) {
		        msg[i] = "上传失败，文件过大！";
		        Util.clearTMPFolder();
		        continue;
			}
			//此处使用UUID，防止文件重名
			File targetFile = new File(getSavePath() + "\\" + UUID.randomUUID().toString() + System.currentTimeMillis() + getUploadFileName()[i].substring(getUploadFileName()[i].indexOf(".")));
//			File targetFile = new File(getSavePath() + "\\" + getUploadFileName()[i]);
			File targetDir = new File(getSavePath());
			if(!targetDir.exists()) {
				targetDir.mkdirs();
			}
			//文件重名则上能上传
			if(targetFile.exists()) {
		        msg[i] = "上传失败，存在重名文件！";
		        continue;
			}
			if(!targetFile.exists()) {
				targetFile.createNewFile();
			}
			//以服务器的文件保存地址和原文件名建立上传文件输出流
			FileOutputStream fos = new FileOutputStream(getSavePath() + "\\" + targetFile.getName());
			FileInputStream fis = new FileInputStream(files[i]);
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = fis.read(buffer)) > 0){
				fos.write(buffer , 0 , len);
			}
	        fos.close();// 注意：流应当关闭。
	        fis.close();
	        msg[i] = "上传成功！";
	        
	        //文件上传成功后，写数据库记录
	        ResBo resBo = ResBo.getInstance();
	        ResInfo resInfo = new ResInfo();
	        if(shareType.equals("0")) {
	        	resInfo.setTypeId(Integer.parseInt(type));
	        } else {
	        	resInfo.setTypeId(0);
	        }
	        resInfo.setName(uploadFileName[i]);
	        if(iconUrl != null) {
	        	resInfo.setIconUrl(iconUrl);
	        }
	        resInfo.setTag(tag);
	        resInfo.setSummary(resDes);
//	        resInfo.setAttachUrl(targetFile.getPath());//绝对路径
	        resInfo.setAttachUrl(SaveDir.BASE_RESOURCE_DIR + "/" + targetFile.getName());//相对路径
	        resInfo.setUploadUserId(user.getId());
	        resInfo.setUploadTime(new Date());
	        resInfo.setReqPoint(Integer.parseInt(resScore));
	        resInfo.setShareWay(Integer.parseInt(shareType));
	        resInfo.setDownloadCount(0);
	        resInfo.setIsRed(0);
	        if(classId != null && !classId.equals("")) {
	        	resInfo.setClassId(Integer.parseInt(classId));
	        }
	        if(folderId != null && !folderId.equals("")) {
	        	resInfo.setFolderId(Integer.parseInt(folderId));
	        }
	        
	        resBo.addInfo(resInfo);
	        count++;
		}
		//更新用户记录
		user.setScore(user.getScore() + count);
		user.setShareCount(user.getShareCount() + count);
		UserBo.getInstance().updateUser(user);
		return SUCCESS;
	}
	public File getResIcon() {
		return resIcon;
	}
	public void setResIcon(File resIcon) {
		this.resIcon = resIcon;
	}
	public String getResIconContentType() {
		return resIconContentType;
	}
	public void setResIconContentType(String resIconContentType) {
		this.resIconContentType = resIconContentType;
	}
	public String getResIconFileName() {
		return resIconFileName;
	}
	public void setResIconFileName(String resIconFileName) {
		this.resIconFileName = resIconFileName;
	}
	public String getResIconMsg() {
		return resIconMsg;
	}
	public void setResIconMsg(String resIconMsg) {
		this.resIconMsg = resIconMsg;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public String getTag() {
		return tag;
	}
	public void setTag(String tag) {
		this.tag = tag;
	}
	public String getResScore() {
		return resScore;
	}
	public void setResScore(String resScore) {
		this.resScore = resScore;
	}
	public String getResDes() {
		return resDes;
	}
	public void setResDes(String resDes) {
		this.resDes = resDes;
	}
	public String getShareType() {
		return shareType;
	}
	public void setShareType(String shareType) {
		this.shareType = shareType;
	}
	public String getClassId() {
		return classId;
	}
	public void setClassId(String classId) {
		this.classId = classId;
	}
	public String getFolderId() {
		return folderId;
	}
	public void setFolderId(String folderId) {
		this.folderId = folderId;
	}
    
}
